import Vue from 'vue'
import 'normalize.css/normalize.css' // A modern alternative to CSS resets
import ElementUI from 'element-ui'
import 'element-ui/lib/theme-chalk/index.css'
// import locale from 'element-ui/lib/locale/lang/en' // lang i18n
import '@/styles/index.scss' // global css
import '@wangeditor/editor/dist/css/style.css'
import App from './App'
import store from './store'
import router from './router'
import axios from 'axios'
import '@/icons' // icon
// import { get } from 'core-js/core/dict'
// import '@/permission' // permission control
import * as echarts from 'echarts' // npm install echarts --save
// Vue.prototype.mainurl = 'https://www.fedhema.cn/'
// Vue.prototype.islocalhost = ture
import CryptoJS from 'crypto-js'

let encryption = true

const url = window.location.host
let httpsUrl = `https://${url}/`
if (window && (window.location.href.indexOf('localhost') > -1 || window.location.href.indexOf('192.168.2') > -1)) {
  httpsUrl = 'http://192.168.2.10:8306/'


  // httpsUrl= "https://www.fubaozx.cn/"
  // encryption=false

}
Vue.prototype.$echarts = echarts
Vue.use(ElementUI)
Vue.use(router)
Vue.prototype.$http = axios
Vue.prototype.$store = store
Vue.prototype.templatename = 'template' // 项目名称
// Vue.prototype.mainurl = "https://www.fubaozx.cn/"; // 接口
Vue.prototype.mainurl = httpsUrl // 接口
Vue.prototype.$tableHight = (window.innerHeight - 240) + 'px'
function md5Encrypt(text) {
  let h = CryptoJS.MD5(text).toString(CryptoJS.enc.Hex).slice(0, 16).toUpperCase()
  return CryptoJS.enc.Base64.stringify(CryptoJS.enc.Utf8.parse(h)).substring(0, 16)
}

function decrypt(encryptWord) {
  if(typeof encryptWord !== 'string'){
    return encryptWord
  }
  var keyStr = CryptoJS.enc.Utf8.parse(md5Encrypt('拉')) //Latin1 w8m31+Yy/Nw6thPsMpO5fg==
  var decrypt = CryptoJS.AES.decrypt(encryptWord, keyStr, {
    mode: CryptoJS.mode.ECB,
    padding: CryptoJS.pad.Pkcs7
  })
  return CryptoJS.enc.Utf8.stringify(decrypt).toString()
}

var path = Vue.prototype.mainurl
Vue.prototype.$clearTimer = function(time) {
  return time.replace('T', ' ').split('.')[0]
}
// ?address=${data.form.province+data.form.city+data.form.area+data.form.address}&`
Vue.prototype.$address = function(address) {
  var this_ = this
  var promise = new Promise(function(resolve, reject) {
    this_
      .$http({
        url: 'https://restapi.amap.com/v3/geocode/geo',
        method: 'get',
        data: {
          address: address,
          key: '3e2ed72107f91ba0e8a4f25e297eba78'
        },
        params: {
          address: address,
          key: '3e2ed72107f91ba0e8a4f25e297eba78'
        },
        headers: {
          'Content-Type': 'application/json'
        }
      })
      .then(
        (result) => {
          if (encryption) {


            const decryptedData = decrypt(result.data.data);
            try {
              // 检查解密后的内容是否为字符串且不为空
              if (typeof decryptedData === 'string' && decryptedData.trim() !== '') {
                result.data.data = JSON.parse(decryptedData);
              } else {
                result.data.data = decryptedData;
              }
            } catch (e) {
              // 当解析失败时，保留原始解密数据而不是抛出异常
              result.data.data = decryptedData;
            }
            resolve(result.data)
          } else {
            resolve(result.data)
          }

        },
        (result) => {
          if (result.response.status === 403) {
            localStorage.removeItem('admin_shop_token')
            this_.$router.push('/login')
          }
          reject(result)
        }
      )
  })
  return promise
}
Vue.prototype.request = function(url, method, data) {
  var token = localStorage.getItem('admin_shop_token')
  var this_ = this
  var url_ = path + url
  var promise = new Promise(function(resolve, reject) {
    this_
      .$http({
        url: url_,
        method: method,
        data: data,
        params: method === 'get' || method === 'GET' ? data : '',
        headers: {
          'Content-Type': 'application/json',
          business: token
        }
      })
      .then(
        (result) => {
          if(result.data.errno == 1) {
            ElementUI.Message.error(result.data.errmsg)
          }
          if (encryption) {
            try {
              const decryptedData = decrypt(result.data.data);
              // 检查解密后的内容是否为字符串且不为空
              if (typeof decryptedData === 'string' && decryptedData.trim() !== '') {
                result.data.data = JSON.parse(decryptedData);
              } else {
                result.data.data = decryptedData;
              }
            } catch (e) {
              // 当解析失败时，保留原始解密数据而不是抛出异常
              // result.data.data = decryptedData;
            }
            resolve(result.data)
          } else {
            resolve(result.data)
          }
        },
        (result) => {

          if (result.response.status === 403) {
            localStorage.removeItem('admin_shop_token')
            this_.$router.push('/login')
            router.push('/login')
          }
          reject(result)
        }
      )
  })
  return promise
}
Vue.prototype.getToken = function() {
  var this_ = this
  var url_ = path + 'business/uploadToken/'
  var token = localStorage.getItem('admin_shop_token')
  var promise = new Promise(function(resolve, reject) {
    this_
      .$http({
        url: url_,
        method: 'get',
        data: {},
        params: {},
        headers: {
          'Content-Type': 'application/json',
          business: token
        }
      })
      .then(
        (result) => {
          if (encryption) {

            const decryptedData = decrypt(result.data.data);
            try {
              // 检查解密后的内容是否为字符串且不为空
              if (typeof decryptedData === 'string' && decryptedData.trim() !== '') {
                result.data.data = JSON.parse(decryptedData);
              } else {
                result.data.data = decryptedData;
              }
            } catch (e) {
              // 当解析失败时，保留原始解密数据而不是抛出异常
              result.data.data = decryptedData;
            }
            resolve(result.data)
          } else {
            resolve(result.data)
          }
        },
        (result) => {
          if (result.response.status === 403) {
            localStorage.removeItem('admin_shop_token')
          }
          reject(result)
        }
      )
  })
  return promise
}

router.beforeEach((to, from, next) => {
  document.title = `${to.meta.title ? to.meta.title : '商家管理后台'}`

  if (to.matched.length === 0) {
    next('/404')
  } else {
    next()
  }
})
// set ElementUI lang to EN
// Vue.use(ElementUI, { locale })
// 如果想要中文版 element-ui，按如下方式声明

Vue.config.productionTip = false

new Vue({
  el: '#app',
  router,
  store,
  render: (h) => h(App)
})
